package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    /**
     *
     * @param shoppingCartDTO
     */
    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //新建购物车
        ShoppingCart shoppingCart = new ShoppingCart();
        //传递的数据copy给购物车
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        //id
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //id找购物车数据
        ShoppingCart cart = shoppingCartMapper.getByCondition(shoppingCart);
        if (cart != null) {
        //认为商品已经在购物车， 设置number为之前的数量+1，执行update操作
            cart.setNumber(cart.getNumber() + 1);
            shoppingCartMapper.update(cart);
        } else {
        // 没有查到，获取商品数据，执行insert操作
            Long dishId = shoppingCartDTO.getDishId();
            cart = new ShoppingCart();
            // 设置创建时间
            cart.setCreateTime(LocalDateTime.now());
            // 设置用户id
            cart.setUserId(BaseContext.getCurrentId());
            // 设置数量为1
            cart.setNumber(1);
            if (dishId != null) {
                // 添加的是菜品
                Dish dish = dishMapper.getId(dishId);
                cart.setDishFlavor(shoppingCartDTO.getDishFlavor());
                cart.setName(dish.getName());
                cart.setImage(dish.getImage());
                cart.setAmount(dish.getPrice());
                cart.setDishId(dishId);
            } else {
                // 添加的是套餐
                SetmealVO setmealVO = setmealMapper.getByIdWithDish(shoppingCartDTO.getSetmealId());
                cart.setName(setmealVO.getName());
                cart.setImage(setmealVO.getImage());
                cart.setAmount(setmealVO.getPrice());
                cart.setSetmealId(shoppingCartDTO.getSetmealId());
            }
            shoppingCartMapper.insert(cart);
        }
    }

    /**
     * 查询购物车
     * @return
     */
    @Override
    public List<ShoppingCart> showShoppingCart() {

        return shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
    }

    /**
     * 清空购物车
     */
    @Override
    public void cleanShoppingCart() {
        shoppingCartMapper.cleanShoppingCart(BaseContext.getCurrentId());
    }
}
